const sys = require(`./system.js`)
const title = '助学抢购'
const $ = sys.$(title)

sys.run($, 'task:one', (resList, cookie, index, username, password, item) => {
    return new Promise(async resolve => {
        // 请求接口
        const size = item.size
        const day = item.day

        const list = await $.publicJS.equitiesList($, cookie, size, day)
        // taskResp = username + "---" + await rushBuy(cookie, cacheSize, cacheDay) + '\n' + taskResp
        // 是否购买
        if (list && list.length > 0) {
            // let couponList = $.localStorage.get('couponList', 'localStorage') || []
            let couponList = $.localStorage.get(`couponList-task:one`, 'localStorage-common') || []
            console.log(Date.now(), '优惠卷 couponList', couponList)
            for (let index = 0; index < list.length; index++) {
                const it = list[index]
                console.log(Date.now(), '抢购第' + index + '个', it)

                let coupon = couponList.length > 0 ? couponList[0] : {}
                console.log(Date.now(), '优惠卷 coupon', coupon);
                const resp = await $.publicJS.buy($, cookie, it.id, coupon.id)
                // 追加信息
                resList.push({
                    '序号': index + 1,
                    username,
                    it,
                    coupon: {
                      id: coupon.id,
                      amount: coupon.amount,
                      day: coupon.day,
                    },
                    resp
                })
                // 删除优惠卷
                if (resp.code == 200 && coupon.id) {
                    let idx = couponList.findIndex(it => it.id == coupon.id)
                    if (idx > -1) {
                        couponList.splice(idx, 1)
                    }
                    $.localStorage.set('couponList-task:one', couponList, 'localStorage-common')
                }
            }
        }
        resolve(resList)
    })
}, (resList) => {
    console.log('任务结束 resList:', resList)
    if (resList && resList.length > 0) {
        const resListStr = JSON.stringify(resList, null, 2)
        $.notify.sendNotify(title, resListStr)
    }
})
